import cloud from '@lafjs/cloud'
import { baiwangInvoice } from '@/uni/invoice/baiwangInvoiceUtils'

export default async function (ctx: FunctionContext) {
  //查询企业标识
  const { data } = await cloud.invoke("uni/invoice/queryUniqueSign_noauth", { ...ctx })

  const json_data = {
    "qyId": data.qyId,
    "ddlsh": ctx.body.ddlsh,
    "zfr": ctx.body.zfr,
    zfyy: ctx.body.zfyy,
  };

  let resp = await baiwangInvoice({
    data: json_data,
    url: "/cloud/invoiceCancel"
  })

  //修改发票状态
  await cloud.nw.db.update({
    dbName: "invoicing",
    whereJson: { out_trade_no: ctx.body.ddlsh },
    dataJson: { invoiceCancelParams: json_data } //红冲发票的参数
  });

  //红冲日志
  await cloud.nw.db.add({
    dbName: "invoice-cancel-log",
    dataJson: {
      "ddlsh": ctx.body.ddlsh,
      "result": resp
    },
    cancelAddTime: false
  });

  if (resp.code == 0) {
    //更改发票状态
    await cloud.invoke("uni/invoice/queryOrder_noauth", { ...ctx, body: { ddlsh: ctx.body.ddlsh } })
    return cloud.utils.requestReturn({ data: resp.message })
  } else {
    return cloud.utils.requestReturn({ code: 500, msg: resp.renson })
  }
}
